package environment.player;

import environment.Pitch;
import environment.Team;
import ain.*;
import ain.impr.*;
import util.Vector;

public class ImprPlayer extends AbstractPlayer
{
	public ImprPlayer(Pitch pitch, Vector position, Team team)
	{
		super(pitch, position, team);
	}
	
	public void addImmuneNetwork()
	{
		antibodies.add(new ImprShootAntibody(this, pitch));
		antibodies.add(new ImprPassAntibody(this, pitch));
		antibodies.add(new ImprKickAntibody(this, pitch));
		antibodies.add(new ImprChaseAntibody(this, pitch));
		antibodies.add(new ImprTrackAntibody(this, pitch));
		antibodies.add(new ImprGuardAntibody(this, pitch));
		
		this.immuneNetwork = new ImmuneNetwork(antibodies);
	}
	
	public void kick(Vector impulse)
	{
		if (pitch.getBall().getVelocity().magnitude() < 0.1)
		{
			// add 20% noise to impulse
			Vector noise = new Vector(Math.random() * 2 - 1, Math.random() * 2 - 1);
			noise.normalize();
			noise.limit(impulse.magnitude() * 0.3);
			impulse.add(noise);
			
			// are we within kicking range?
			Vector distanceToBall = Vector.substract(pitch.getBall().getPosition(), position);
			if (distanceToBall.magnitude() > KICKING_RANGE)
			{
				walk(pitch.getBall().getPosition());
			}
			else
			{
				// can only shoot if ball is not moving
				if (pitch.getBall().getVelocity().magnitude() < 0.1)
				{
					long timeSinceLastKick = System.currentTimeMillis() - lastKickStartingTime;
					
					if (timeSinceLastKick > KICK_DURATION)
					{
						pitch.getBall().kick(impulse.limit(MAX_KICK_IMPULSE));
						lastKickStartingTime = System.currentTimeMillis();
					}
				}
			}
		}
	}
	
	public void walk(Vector target)
	{
		if (pitch.getBall().getVelocity().magnitude() < 0.1)
		{
			// walks within half kickrange of target position
			
			// check if kicking movement is still in progress
			long timeSinceLastKick = System.currentTimeMillis() - lastKickStartingTime;
			if (timeSinceLastKick >= KICK_DURATION)
			{
				Vector distance = Vector.substract(target, position);
				// goal not yet reached?
				if (distance.magnitude() > KICKING_RANGE/2)
				{
					distance.limit(MAX_SPEED);
					velocity = distance;
					position.add(velocity);
				}
			}
		}
	}
}
